package com.minyue.config;

import com.minyue.enums.MapperMethodEnum;
import com.minyue.pojo.Configuration;
import com.minyue.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author ：minyue
 * @date ：Created in 2021/7/22 11:20 下午
 * @description：
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        for (MapperMethodEnum methodEnum : MapperMethodEnum.values()) {
            List<Element> selectElements = rootElement.selectNodes(methodEnum.getMethod());
            selectElements.forEach(selectElement -> {
                String id = selectElement.attributeValue("id");
                String paramterType = selectElement.attributeValue("paramterType");
                String resultType = selectElement.attributeValue("resultType");
                String sql = selectElement.getTextTrim();
                String key = namespace + "." + id;
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setParamterType(paramterType);
                mappedStatement.setResultType(resultType);
                mappedStatement.setSqlText(sql);
                mappedStatement.setMethodEnum(methodEnum);
                configuration.getMappedStatementMap().put(key, mappedStatement);
            });
        }
    }
}
